from web3 import Web3

# Your Infura Project ID
# INFURA_SECRET_KEY = '7fe353dd8591489db345b657ebe5c910'
INFURA_SECRET_KEY = 'a13269733d7b4670b050ca945ef1daaa'

# get w3 endpoint by network name
def get_w3_by_network(network='mainnet'):
    infura_url = f'https://{network}.infura.io/v3/{INFURA_SECRET_KEY}' # 接入 Infura 节点
    # https://mainnet.infura.io/v3/a13269733d7b4670b050ca945ef1daaa
    w3 = Web3(Web3.HTTPProvider(infura_url))
    return w3

def transfer_eth(w3,from_address,private_key,target_address,amount,gas_price=5,gas_limit=21000,chainId=4):
    from_address = Web3.toChecksumAddress(from_address)
    target_address = Web3.toChecksumAddress(target_address)
    nonce = w3.eth.getTransactionCount(from_address) # 获取 nonce 值
    params = {
        'from': from_address,
        'nonce': nonce,
        'to': target_address,
        'value': w3.toWei(amount, 'ether'),
        'gas': gas_limit,
        # 'gasPrice': w3.toWei(gas_price, 'gwei'),
        'maxFeePerGas': w3.toWei(gas_price, 'gwei'),
        'maxPriorityFeePerGas': w3.toWei(gas_price, 'gwei'),
        'chainId': chainId,
    }
    try:
        signed_tx = w3.eth.account.signTransaction(params, private_key=private_key)
        txn = w3.eth.sendRawTransaction(signed_tx.rawTransaction)
        return {'status': 'succeed', 'txn_hash': w3.toHex(txn), 'task': 'Transfer ETH'}
    except Exception as e:
        return {'status': 'failed', 'error': e, 'task': 'Transfer ETH'}


def main():
    
    # 🐳 Task 1: 接入并读取区块链信息

    # 接入 Web3
    w3 = get_w3_by_network(network='goerli')
    # w3 = get_w3_by_network(network='mainnet')
    
    # 检查接入状态
    assert w3.isConnected()
    print(f"主网接入状态{w3.isConnected()}")

    # 当前区块高度
    print(w3.eth.block_number)

    # V神 3号钱包地址
    vb = '0x220866b1a2219f40e72f5c628b65d54268ca3a9d'

    # 地址格式转换
    address = Web3.toChecksumAddress(vb)

    # 查询地址 ETH余额
    balance = w3.eth.get_balance(address) / 1e18
    print(f'V神地址余额: {balance = } ETH')

if __name__ == "__main__":
    main()